// pages/category/category.js
import api from "../../utils/util"
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    activeKey: 0,
    hello: "hello",
    active: 0,
    categorys: [],
    products: [{
        imgs: "https://z3.ax1x.com/2021/03/25/6qvvB4.jpg",
        title: "日式和风懒人沙发",
        subTitle: '日本面料，简约条纹',
        price: 189,
      },
      {
        imgs: "https://z3.ax1x.com/2021/03/25/6qvvB4.jpg",
        title: "日式和风懒人沙发",
        subTitle: '日本面料，简约条纹',
        price: 189,
      }
    ]
  },

  async getAllCategory() {
    const result = await api.get("/category/list");
    if (result) {
      this.setData({
        categorys: result.data
      })
    }
  },
  onClose(event) {
    const {
      position,
      instance
    } = event.detail;
    switch (position) {
      case 'left':
      case 'cell':
        instance.close();
        break;
      case 'right':
        Dialog.confirm({
          message: '确定删除吗？',
        }).then(() => {
          instance.close();
        });
        break;
    }
  },
  async switch (e, options) {
    console.log("switch")
    let index;
    let id;
    if (e) {
      index = e.currentTarget.dataset['index'];
      id = e.currentTarget.dataset['id'];
    }
    if (options) {
      index = options.index;
      id = options.id;
    }

    const result = await api.post("/product/page", {
      categoryId: id
    })
    console.log(result)
    this.setData({
      active: index,
      products: result.data.records
    })
  },
  onChange(event) {
    Notify({
      type: 'primary',
      message: event.detail
    });
  },
  onSearch(){
wx.navigateTo({
  url: '/pages/search/search',
})
  },
  toDetail(e) {
    const {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/productDetail/productDetail?id=${id}`,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    await this.getAllCategory();
    const category = app.globalData.category;
    if (JSON.stringify(category) !== '{}') {
      await this.switch(null, {
        id: category.id,
        index: category.index
      });
    } else {
      await this.switch(null, {
        id: this.data.categorys[0].id,
        index: 0
      });
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const options = app.globalData.category;
    console.log(options)
    if (options) {
      console.log("{}")
      this.switch(null, options);
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})